﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;
using System.Threading;

namespace Twin
{
    /// <summary>
    /// 远端连接类
    /// </summary>
    public class RemoteConnection : Constants
    {
        // 串行端口资源
        SerialPort sp = new SerialPort();
        // (ms)最大等待时间---等待第一段数据
        public const int WAIT_1ST = 10000;
        // (ms)最大等待时间---等待下一段数据
        public const int WAIT_NEXT = 200;
        // 定时器
        public System.Timers.Timer timer;
        // 是否继续接收
        public bool keepReading;
        // 定时器是否到时
        public bool timerOver;
        private TConsole fMain;

        public string COMi;

        
        public RemoteConnection()
        {
        //    Init();
        //    Open();
        }

        public RemoteConnection(TConsole main)
        {
            this.fMain = main;
            //串口初始化
            Init();
            //打开串口
            Open();

            //fMain
        }

        /// <summary>
        /// 打开串口
        /// </summary>
        public void Open()
        {
            try
            {
                sp.Open();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 关闭串口
        /// </summary>
        public void Close()
        {
            try
            {
                sp.Close();
            }
            catch (Exception ex)
            {
                //fMain.txtStationsHistory.BeginInvoke(fMain.m_delShowLogTxt, "Error:" + ex.Message, 2);
                //fMain.txtOUT.Text = "Error:" + ex.Message;
            }
        }

        /// <summary>
        /// 返回串口对象状态
        /// </summary>
        public bool IsOpen
        {
            get
            {
                return sp.IsOpen;
            }
        }

        /// <summary>
        /// 串口注册信息
        /// </summary>
        public void Init()
        {
            //串口号
            //sp.PortName = OperateIniFile.ReadIniData("PortInfo", "COMx", "", ConfigIO.SensorSim_ini);
            string t;
            t = OperateIniFile.ReadIniData("PortInfo", COMi, "", ConfigIO.SensorMonitor_ini);
            sp.PortName = t;
            
            //波特率
            sp.BaudRate = 19200;
            //数据位
            sp.DataBits = 8;
            //一个停止位
            sp.StopBits = System.IO.Ports.StopBits.One;
            //无奇偶校验
            sp.Parity = System.IO.Ports.Parity.None;
            //设置串行端口输入/输出缓冲区的大小
            sp.ReadBufferSize = 65536;
            sp.WriteBufferSize = 65536;
            //准备就绪
            sp.DtrEnable = true;
            sp.RtsEnable = true;
        }

        /// <summary>
        /// 写入数据到设备中
        /// </summary>
        public void WritePort(byte[] buffer, int offset, int count)
        {
            if (IsOpen)
            {
                try
                {
                    sp.Write(buffer, offset, count);//使用缓冲区的数据将指定数量的字节写入串行端口
                }
                catch
                {
                    //fMain.txtStationsHistory.BeginInvoke(fMain.m_delShowLogTxt, "向串口写入数据失败，请重启XTOOL", 2);
                    //fMain.txtOUT.Text = "向串口写入数据失败";
                }
             
                //sp.DiscardOutBuffer();//丢弃来自串行驱动程序的传输缓冲区的数据
            }
        }

        /// <summary>
        /// 从设备中读取数据
        /// </summary>
        public void ReadPort(byte[] buffer, int offset, int count)
        {
            if (IsOpen)
            {
                sp.Read(buffer, offset, count);//从输入缓冲区读取一些字节并将那些字节写入字节数组指定的偏移量处
                sp.DiscardInBuffer();//丢弃来自串行驱动程序的接收缓冲区的数据。
            }
        }

        /// <summary>
        /// 定时器到时
        /// </summary>
        public void timerIsOver(object source, System.Timers.ElapsedEventArgs e)
        {
            timerOver = true;
        }

        /// <summary>
        /// 创建一个定时器
        /// </summary>
        public void StartTimer(int Interval)
        {
            //定时器是否到时
            timerOver = false;

            if (timer != null)
            {
                timer.Enabled = false;
            }
            timer = new System.Timers.Timer();
            timer.Interval = Interval;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timerIsOver);
            timer.AutoReset = false;
            timer.Enabled = true;
        }

        /// <summary>
        /// 连接确认/串口握手
        /// </summary>
        public bool ConnectionVerify()
        {
            //检查串口对象状态
            string result = string.Empty;
            return ConnectionVerify(ref result);
        }
        
        
        
        /// <summary>
        /// 连接确认/串口握手
        /// </summary>
        public bool ConnectionVerify(ref string result)
        {
            //检查串口对象状态
            if (IsOpen){
                try{
                    sp.DiscardInBuffer();
                    sp.DiscardOutBuffer();
                    sp.Write("A");
                }
                catch{
                    //fMain.txtStationsHistory.BeginInvoke(fMain.m_delShowLogTxt, "向串口写入数据失败，请重启XTOOL", 2);
                    //fMain.txtOUT.Text = "向串口写入数据失败";
                    return false;
                }
                //sp.DiscardOutBuffer();
                //fMain.txtStationsHistory.BeginInvoke(fMain.m_delShowLogTxt, "发送指令：A", 1);
                //fMain.txtOUT.Text = "发送指令：A";
                    
                byte[] pData = null;
                try{
                    pData = ReadByte();
                }
                catch{
                    //fMain.txtStationsHistory.BeginInvoke(fMain.m_delShowLogTxt, "从串口读取数据失败，请重启XTOOL", 2);
                    //fMain.txtOUT.Text = "从串口读取数据失败";
                    return false;
                }
                result = Encoding.Default.GetString(pData);
                //fMain.txtStationsHistory.BeginInvoke(fMain.m_delShowLogTxt, "响应内容：" + "[" + FormatHelper.ByteToString(pData) + "]" + result, 1);
                //fMain.txtOUT.Text = "响应内容：" + "[" + FormatHelper.ByteToString(pData) + "]" + result;

                //if (result.IndexOf("R") != -1 && FormatHelper.ByteToString(pData).Substring(0, 2) != "48"){
                //    return true;
                //}
            }
            return false;
        }


        /// <summary>
        /// 读取数据（字符串）
        /// </summary>
        public string ReadStr()
        {
            //等待第一段数据
            StartTimer(WAIT_1ST);

            //默认一直循环
            keepReading = true;

            do
            {
                Application.DoEvents();

                //缓冲区中数据的字节数 大于等于1
                if (sp.BytesToRead >= 1)
                {
                    keepReading = false;
                }
                //定时时间到
                else if (timerOver)
                {
                    keepReading = false;
                }
            } while (keepReading);

            //读取所有数据
            string str = sp.ReadExisting();
            //丢弃来自串行驱动程序的传输缓冲区的数据。
            sp.DiscardInBuffer();

            return str;
        }

        public byte[] ReadByte()
        {
            //等待第一段数据
            StartTimer(WAIT_1ST);

            //默认一直循环
            keepReading = true;

            do
            {
                Application.DoEvents();

                //缓冲区中数据的字节数 大于等于1
                if (sp.BytesToRead >= 1)
                {
                    keepReading = false;
                }
                //定时时间到
                else if (timerOver)
                {
                    keepReading = false;
                }
            } while (keepReading);

            //读取所有数据
            //获取接收缓冲区中数据的字节数
           int count = sp.BytesToRead;
            byte[] bytes = new byte[count];

            //读取所有数据
            ReadPort(bytes, 0, count);
            //丢弃来自串行驱动程序的传输缓冲区的数据。
            sp.DiscardInBuffer();

            return bytes;
        }


        /// <summary>
        /// 获取端口返回数据
        /// </summary>
        public byte[] ReadBytes(ref int count)
        {
            //等待第一段数据
            StartTimer(WAIT_1ST);

            //默认一直循环
            keepReading = true;

            do
            {
                Application.DoEvents();

                //缓冲区中数据的字节数 大于等于1
                if (sp.BytesToRead >= 1)
                {
                    keepReading = false;
                }
                //定时时间到
                else if (timerOver)
                {
                    keepReading = false;
                }
            } while (keepReading);

            count = sp.BytesToRead;

            //等待下一段数据
            StartTimer(WAIT_NEXT);

            //默认一直循环
            keepReading = true;

            do
            {
                Application.DoEvents();

                //缓冲区中数据的字节数 发生变化
                if (sp.BytesToRead > count)
                {
                    count = sp.BytesToRead;

                    //等待下一段数据
                    StartTimer(WAIT_NEXT);
                }
                //超出接收范围 或 定时时间到
                if (sp.BytesToRead >= ORDER_MAX_LEN || timerOver)
                {
                    keepReading = false;
                }
            } while (keepReading);

            //获取接收缓冲区中数据的字节数
            count = sp.BytesToRead;
            byte[] bytes = new byte[count];

            //读取所有数据
            ReadPort(bytes, 0, count);

            return bytes;
        }

        /*
        /// <summary>
        /// 写入数据
        /// 1.按全部写入
        /// 2.按分页写入
        /// 3.按字节写入
        /// </summary>
        public bool Write(byte[] bytes, int type, int pageUnit, long pageIndex, int pages, long op, 
            Main main, byte mapType, byte bProperty, string cfg_crc, string cfg_index)
        {
            bool result = false;
            if (op == 0)
            {
                //检查串口对象状态
                if (IsOpen)
                {
                 
                    bool isConnected = ConnectionVerify();//首次连接‘A’‘R’

                    if (!isConnected)
                    {
                        main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "无响应（错误）", 2);
                        return result;
                    }
                }
                else
                {
                    return result;
                }
            }

            //可选字符
            string spack = "";
            if (FormatHelper.TestBit(bProperty, 1))
            {
                string dt = "";
                dt += Convert.ToInt32(DateTime.Now.ToString("yy")).ToString("X2");
                dt += Convert.ToInt32(DateTime.Now.Month).ToString("X2");
                dt += Convert.ToInt32(DateTime.Now.Day).ToString("X2");
                dt += Convert.ToInt32(DateTime.Now.Hour).ToString("X2");
                dt += Convert.ToInt32(DateTime.Now.Minute).ToString("X2");
                dt += Convert.ToInt32(DateTime.Now.Second).ToString("X2");
                spack = SetSpack(spack, "DT", dt);
            }
            spack = SetSpack(spack, "SLU", pageIndex.ToString("X8") + pages.ToString("X4") + pageUnit.ToString("X2"));
            spack = FormatHelper.str2hex(spack, "gbk", false);
            byte[] spackBytes = FormatHelper.StringToByte(spack);

            //帧头
            byte[] inst = WriteRegistrationOrder(bProperty, bytes.Length + spackBytes.Length + Constants.LEN_END, mapType);

            //发送帧头
            //main.UpdateaRecord("发送帧头：" + FormatHelper.ByteToString(inst));
            main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "发送帧头：\r\n" + FormatHelper.ByteToString(inst), 1);
            StrHelper.write("log\\serial.log", "发送帧头：" + FormatHelper.ByteToString(inst) + "\r\n");
            WritePort(inst, 0, inst.Length);

            //设备业务包长度，正文校验
            byte[] newBytes = DgvOperate.PacketBytes(bytes, mapType, cfg_crc, cfg_index, spackBytes);

            //发送报文
           // main.UpdateaRecord("发送报文：" + FormatHelper.ByteToString(newBytes));
            main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "发送报文：\r\n" + FormatHelper.ByteToString(newBytes), 1);
            StrHelper.write("log\\serial.log", "发送报文：" + FormatHelper.ByteToString(newBytes) + "\r\n");
            WritePort(newBytes, 0, newBytes.Length);

            //获取响应数据
            int count = 0;
            byte[] rspBytes = ReadBytes(ref count);
           // main.UpdateaRecord("响应数据：" + FormatHelper.ByteToString(rspBytes));
            main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "响应数据：\r\n" + FormatHelper.ByteToString(rspBytes), 1);
            StrHelper.write("log\\serial.log", "响应数据：" + FormatHelper.ByteToString(rspBytes) + "\r\n");

            //校验响应
            if (IsBytesAnswerRightOfWrite(rspBytes, count,main))
            {
                result = true;
            }

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="cfg_crc"></param>
        /// <param name="cfg_index"></param>
        /// <returns></returns>
        public bool Write(byte[] bytes,byte bProperty,Main main)
        {
                bool result = false;
                //检查串口对象状态
                if (IsOpen)
                {
                    bool isConnected = ConnectionVerify();//首次连接‘A’‘R’
                    if (!isConnected)
                    {
                        main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "无响应（错误）", 2);
                        return result;
                    }
                }
                else
                {
                    return result;
                }
                byte[] inst = WriteRegistrationOrder(bProperty, bytes.Length + Constants.LEN_END - 4, 0);
                WritePort(inst, 0, inst.Length);
                main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "发送帧头：\r\n" + FormatHelper.ByteToString(inst), 1);
                //设备业务包长度，正文校验

                byte[] newBytes = new byte[bytes.Length + 5];

                //设置业务包长度
                byte[] lenPackBytes = BitConverter.GetBytes(bytes.Length + Constants.LEN_END );
                lenPackBytes[0] = lenPackBytes[0];
                lenPackBytes[1] = lenPackBytes[1];
                Array.Copy(lenPackBytes, 0, newBytes, 0, lenPackBytes.Length);
                Array.Copy(bytes, 0, newBytes, 2, bytes.Length);
                newBytes[bytes.Length + 2] = 0;
                //设置CRC
                long crc = Constants.GetCrc(newBytes, 0, newBytes.Length - 2);
                byte[] crcBytes = BitConverter.GetBytes(crc);
                Array.Copy(crcBytes, 0, newBytes, bytes.Length + 3, 2);
                //写入CRC
                WritePort(newBytes, 0, newBytes.Length);
                main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "发送报文：\r\n" + FormatHelper.ByteToString(newBytes), 1);
              
                int  count = 0;
               byte[] rspBytes = ReadBytes(ref count);
                //校验响应
                if (IsBytesAnswerRightOfWrite(rspBytes, count, main))
                {
                    result = true;
                }
                main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "响应数据：\r\n" + FormatHelper.ByteToString(rspBytes), 1);
                StrHelper.write("log\\serial.log", "响应数据：" + FormatHelper.ByteToString(rspBytes) + "\r\n");
                return result;
        }
        */

        /// <summary>
        /// 设置可选字符
        /// </summary>
        public static string SetSpack(string spack, string name, string data)
        {
            if (spack != "")
            {
                spack += ";" + name + "=" + data;
            }
            else
            {
                spack += name + "=" + data;
            }
            return spack;
        }

        /*
        /// <summary>
        /// 读取数据
        /// 1.按全部读取
        /// 2.按分页读取
        /// 3.按字节读取
        /// </summary>
        public byte[] Read(int type, int pageUnit, long pageIndex, int pages, int staId, long op, Main main, byte mapType)
        {
            //读取的数据
            byte[] bytes = null;

            if(op==0){
                //检查串口对象状态
                if(IsOpen){
                    string result = string.Empty;
                    bool isConnected = ConnectionVerify(ref result);//首次连接‘A’‘R’
                    if (!isConnected){
                        if (result.Length == 0) result = "无响应";
                        
                       // MessageBox.Show("无响应（错误）");
                        main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "响应错误：\r\n" + result, 2);
                        return bytes;
                    }
                }
                else{
                    return bytes;
                }
            }

            //可选字符
            string spack = "";
            spack = SetSpack(spack, "SLU", pageIndex.ToString("X8") + pages.ToString("X4") + pageUnit.ToString("X2"));
            spack = FormatHelper.str2hex(spack, "gbk", false);
            byte[] spackBytes = FormatHelper.StringToByte(spack);

            //帧头
            byte[] inst = ReadRegistrationOrder(spackBytes.Length + Constants.LEN_END, mapType);

            //发送帧头
            //main.UpdateaRecord("发送帧头：" + FormatHelper.ByteToString(inst));
            main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "发送帧头：\r\n" + FormatHelper.ByteToString(inst), 1);
            StrHelper.write("log\\serial.log", "发送帧头：" + FormatHelper.ByteToString(inst) + "\r\n");
            WritePort(inst, 0, inst.Length);

            //设备业务包长度，正文校验
            byte[] newBytes = DgvOperate.PacketBytes(spackBytes);

            //发送报文
            //main.UpdateaRecord("发送报文：" + FormatHelper.ByteToString(newBytes));
            main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "发送报文：\r\n" + FormatHelper.ByteToString(newBytes), 1);
            StrHelper.write("log\\serial.log", "发送报文：" + FormatHelper.ByteToString(newBytes) + "\r\n");
            WritePort(newBytes, 0, newBytes.Length);

            //获取响应数据
            int count = 0;
            byte[] rspBytes = null;
            try { rspBytes = ReadBytes(ref count); }
            catch {
                main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "读取串口数据失败，请重启XTOOL", 2);
            }
         

            if (rspBytes == null || rspBytes.Length == 0 || rspBytes.Length < LEN_HEAD)
            {
                main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "无响应（错误）",2);
                return null;
            }

            //获取帧长度，将多余数据舍弃
            int len = rspBytes[CH_LEN_0] + rspBytes[CH_LEN_1] * 256 + 1;//因为帧长度被-1，所以计算时需+1

            if (len == 0)
            {
                //MessageBox.Show("无响应（错误）");
                main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "无响应（错误）", 2);
                return null;
            }
            if (len > rspBytes.Length)
            {
              //  MessageBox.Show("帧长度有误");
                main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "帧长度有误", 2);
                return null;
            }

            byte[] tempBytes = new byte[len];
            for (int i = 0; i < len; i++)
            {
                tempBytes[i] = rspBytes[i];
            }
            //main.UpdateaRecord("响应数据：" + FormatHelper.ByteToString(tempBytes));
            main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "响应数据：\r\n" + FormatHelper.ByteToString(tempBytes), 1);
            StrHelper.write("log\\serial.log", "响应数据：" + FormatHelper.ByteToString(tempBytes) + "\r\n");

            //可选字符所占字节
            int spack_count = 0;
            if (tempBytes.Length > CH_PROPERTY_1 + 1)
            {
                if (FormatHelper.TestBit(tempBytes[CH_PROPERTY_1], 2))
                {
                    for (int j = LEN_HEAD + LEN_LENPACK; j < tempBytes.Length - LEN_CRC; j++)
                    {
                        spack_count++;
                        if (tempBytes[j] == 0)
                        {
                            break;
                        }
                    }
                }
            }

            if (tempBytes.Length > CH_PROPERTY_1 + 1)
            {
                //特例情况
                if (FormatHelper.TestBit(tempBytes[CH_PROPERTY_1], 4))
                {
                    //将帧头、业务包长度、CFG_CRC长度、CFG_INDEX长度和正文校验长度去除
                    bytes = new byte[tempBytes.Length - LEN_HEAD - LEN_LENPACK - LEN_CFG_CRC - LEN_CFG_INDEX - spack_count - LEN_CRC];
                    for (int j = LEN_HEAD + LEN_LENPACK + LEN_CFG_CRC + LEN_CFG_INDEX + spack_count; j < tempBytes.Length - LEN_CRC; j++)
                    {
                        bytes[j - LEN_HEAD - LEN_LENPACK - LEN_CFG_CRC - LEN_CFG_INDEX - spack_count] = tempBytes[j];
                    }
                }
                else
                {
                    //将帧头、业务包长度和正文校验长度去除
                    bytes = new byte[tempBytes.Length - LEN_HEAD - LEN_LENPACK - spack_count - LEN_CRC];
                    for (int j = LEN_HEAD + LEN_LENPACK + spack_count; j < tempBytes.Length - LEN_CRC; j++)
                    {
                        bytes[j - LEN_HEAD - LEN_LENPACK - spack_count] = tempBytes[j];
                    }
                }
            }

            if (pageIndex + 1 == pages)
            {
                //是否需要响应---后面需要修改---
                if (FormatHelper.TestBit(tempBytes[CH_PROPERTY_0] + tempBytes[CH_PROPERTY_1] * 256, BIT_ANSWER_NEEDED))
                {
                    byte[] sendReply = ReadAnswerOrder(staId);
                    //发送响应
                   // main.UpdateaRecord("确认响应：" + FormatHelper.ByteToString(sendReply));
                    main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "确认响应：\r\n" + FormatHelper.ByteToString(sendReply), 1);
                    StrHelper.write("log\\serial.log", "确认响应：" + FormatHelper.ByteToString(sendReply) + "\r\n");
                    WritePort(sendReply, 0, sendReply.Length);
                }
            }

            return bytes;
        }
        */



        /*
        /// <summary>
        /// 读取最新数据
        /// ReadBelt
        /// </summary>
        public byte[] ReadBelt(byte[] DateTimeBytes, byte FmtIndex,byte returnIndex, Main main)
        {
            //读取的数据
            byte[] bytes = null;

            //检查串口对象状态
            if (IsOpen)
            {
                bool isConnected = ConnectionVerify();//首次连接‘A’‘R’

                if (!isConnected)
                {
                    main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "无响应（错误）", 2);
                    return bytes;
                }
            }
            else
            {
                return bytes;
            }
            
            //帧头
            byte[] inst = ReadBeltOrder(DateTimeBytes, FmtIndex, returnIndex);

            //发送帧头
           // main.UpdateaRecord("发送帧头：" + FormatHelper.ByteToString(inst));
            main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "发送帧头：\r\n" + FormatHelper.ByteToString(inst), 2);
            StrHelper.write("log\\serial.log", "发送帧头：" + FormatHelper.ByteToString(inst) + "\r\n");
            Thread.Sleep(5);
            WritePort(inst, 0, inst.Length);
            
            //获取响应数据
            int count = 0;
            byte[] rspBytes = ReadBytes(ref count);
          
            if (rspBytes == null || rspBytes.Length == 0)
            {
               // MessageBox.Show("无响应（错误）");
                main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "无响应（错误）", 2);
                return null;
            }
            main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "响应数据：\r\n" + FormatHelper.ByteToString(rspBytes), 1);
            if (rspBytes.Length - 1 < CH_LEN_1)
            {
                main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "无响应（错误）", 2);
                return null;
            }
            //获取帧长度，将多余数据舍弃
            int len = rspBytes[CH_LEN_0] + rspBytes[CH_LEN_1] * 256 + 1;//因为帧长度被-1，所以计算时需+1

            if (len == 0)
            {
                //MessageBox.Show("无响应（错误）");
                main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "无响应（错误）", 2);
                return null;
            }
            if (len > rspBytes.Length)
            {
              //  MessageBox.Show("帧长度有误");
                main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "帧长度有误", 2);
                return null;
            }

            byte[] tempBytes = new byte[len];
            for (int i = 0; i < len; i++)
            {
                tempBytes[i] = rspBytes[i];
            }
            //main.UpdateaRecord("响应数据：" + FormatHelper.ByteToString(tempBytes));
           
            StrHelper.write("log\\serial.log", "响应数据：" + FormatHelper.ByteToString(tempBytes) + "\r\n");

            ////将帧头、业务包长度和正文校验去除
            //bytes = new byte[tempBytes.Length - LEN_HEAD - LEN_LENPACK - LEN_CRC];
            //for (int j = LEN_HEAD + LEN_LENPACK; j < tempBytes.Length - LEN_CRC; j++)
            //{
            //    bytes[j - LEN_HEAD - LEN_LENPACK] = tempBytes[j];
            //}

          //  return bytes;
            return tempBytes;
        }
        */

        /// <summary>
        /// 验证数据是否正确
        /// </summary>
        public bool IsBytesAnswerRight(byte[] echo_bytes, int echo_count)
        {
            bool result = true;
            if (echo_count == 0)
            {
               // MessageBox.Show("无响应（错误）");
                //fMain.txtStationsHistory.BeginInvoke(fMain.m_delShowLogTxt, "无响应（错误）", 2);
                //fMain.txtOUT.Text="无响应（错误）";
                result = false;
            }
            else if (echo_count < LEN_SHORT)
            {
               // MessageBox.Show("响应长度不足（错误）");
                //fMain.txtStationsHistory.BeginInvoke(fMain.m_delShowLogTxt, "响应长度不足（错误）", 2);
                //fMain.txtOUT.Text="响应长度不足（错误）";

                result = false;
            }
            //PACK_START = 0, LEN_SHORT = 32（帧头校验）
            else if (!CheckInfo(echo_bytes, PACK_START, LEN_SHORT))
            {
                //MessageBox.Show("校验（错误）");
                //fMain.txtStationsHistory.BeginInvoke(fMain.m_delShowLogTxt, "校验（错误）", 2);
                //fMain.txtOUT.Text="校验（错误）";
                result = false;
            }
            //DATA_START = 32（正文校验）
            else if (!CheckInfo(echo_bytes, DATA_START, echo_bytes[CH_LEN_PACK_0] + echo_bytes[CH_LEN_PACK_1] * 256 + 4))
            {
                //MessageBox.Show("校验(错误)");
                //fMain.txtStationsHistory.BeginInvoke(fMain.m_delShowLogTxt, "校验（错误）", 2);
                //fMain.txtOUT.Text="校验（错误）";

                result = false;
            }
            return result;
        }

        /*
        /// <summary>
        /// 校验响应
        /// </summary>
        public bool IsBytesAnswerRightOfWrite(byte[] echo_bytes, int echo_count,Main main)
        {
            bool result = true;
            if (echo_count == 0)
            {
               // MessageBox.Show("无响应（错误）");
                main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "无响应（错误）", 2);
                result = false;
            }
            else if (echo_count < LEN_SHORT)
            {
                //MessageBox.Show("响应长度不足（错误）");
                main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "响应长度不足（错误）", 2);
                result = false;
            }
            else if (!CheckInfo(echo_bytes, PACK_START, LEN_SHORT))
            {
                //MessageBox.Show("校验（错误）");
                main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "校验（错误）", 2);
                result = false;
            }
            else if ((echo_bytes[CH_LEN_0] + echo_bytes[CH_LEN_1] * 256) != OP_LEN)
            {
                //MessageBox.Show("数据太长");
                main.txtStationsHistory.BeginInvoke(main.m_delShowLogTxt, "数据太长", 2);
                result = false;
            }
            return result;
        }
        */
    }

    public class ListItem
    {
        public string key { get; set; }
        public string value { get; set; }

        public ListItem(string pKey, string pValue)
        {
            this.key = pKey;
            this.value = pValue;
        }

        public override string ToString()
        {
            return this.key;
        }
    }
}